package com.dxb.yomall.auth.controller;

import com.fasterxml.jackson.core.type.TypeReference;
import com.dxb.common.constant.AuthConstant;
import com.dxb.common.utils.CookieUtils;
import com.dxb.common.utils.IpUtils;
import com.dxb.common.utils.JwtUtils;
import com.dxb.common.utils.R;
import com.dxb.yomall.auth.config.JwtProperties;
import com.dxb.yomall.auth.exception.AuthBizException;
import com.dxb.yomall.auth.feign.MemberFeignService;
import com.dxb.yomall.auth.service.SmsService;
import com.dxb.common.vo.MemberVO;
import com.dxb.yomall.auth.vo.UserLoginVO;
import com.dxb.yomall.auth.vo.UserRegisterVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 登录注册 {@link LoginController}
 *
 * @author Kevin
 * @email: 178676392@qq.com
 */
@EnableConfigurationProperties(JwtProperties.class)
@Controller
public class LoginController {

    @Autowired
    private SmsService smsService;

    @Autowired
    private MemberFeignService memberFeignService;

    /**
     * 校验用户是否存在
     * @param username
     * @return
     */
    @ResponseBody
    @GetMapping("/check/user/{username}")
    public R checkUser(@PathVariable("username") String username) {
        R r = memberFeignService.checkUser(username);
        return r;
    }

    /**
     * 检查手机号是否存在
     * @param mobile
     * @return
     */
    @ResponseBody
    @GetMapping("/check/mobile/{mobile}")
    public R checkMobile(@PathVariable("mobile") String mobile) {
        R r = memberFeignService.checkMobile(mobile);
        return r;
    }


    /**
     * 发送短信验证码
     * @param mobile
     * @return
     */
    @ResponseBody
    @GetMapping("/sms/sendcode")
    public R sendCode (@RequestParam("mobile") String mobile) {
        try {
            smsService.sendCode(mobile);
        } catch (AuthBizException e) {
            return R.error(e.getCode(), e.getMessage());
        }

        return R.ok();
    }

    /**
     * 用户注册
     * @param registerVO
     * @param result
     * @param redirectAttributes
     * @return
     */
    @PostMapping("/reg")
    public String register (@Valid UserRegisterVO registerVO, BindingResult result,
                            RedirectAttributes redirectAttributes) {
        if (result.hasErrors()) {
            // 收集校验错误消息
            Map<String, String> errors = result.getFieldErrors().stream()
                    .collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            redirectAttributes.addFlashAttribute("errors", errors);
            // 校验出错，重定向到注册页面
            // TODO 重定向携带数据, 利用Session原理. 到了目标页面从session中取出数据, 然后删除session中的数据.
            // TODO 分布式 Session 问题
            return "redirect:http://auth.yomall.com/reg.html";
        }

        // 校验验证码
        boolean b = smsService.checkCode(registerVO.getMobile(), registerVO.getCode());
        if (!b) {
            Map<String, String> errors = new HashMap<>();
            errors.put("code", "验证码错误");
            redirectAttributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.yomall.com/reg.html";
        }

        // 调用远程会员注册
        R r = memberFeignService.register(registerVO);
        if (r.getCode() != 0) {
            Map<String, String> errors = new HashMap<>();
            errors.put("msg", r.getData("msg", new TypeReference<String>() {}));
            redirectAttributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.yomall.com/reg.html";
        }

        // 注册成功，重定向到登录页
        return "redirect:http://auth.yomall.com/login.html";
    }

    /**
     * 用户登录：账号密码登录
     * @param vo
     * @return
     */
    @PostMapping("/login")
    public String login(UserLoginVO vo, RedirectAttributes redirectAttributes, HttpSession session) {
        // 调用远程接口
        R r = memberFeignService.login(vo);

        if (r.getCode() != 0) {
            Map<String, String> errors = new HashMap<>();
            String msg = r.getData("msg", new TypeReference<String>() {});
            errors.put("msg", msg);
            redirectAttributes.addFlashAttribute("errors", errors);
            // 登录失败，重定向到登录页面
            return "redirect:http://auth.yomall.com/login.html";
        }

        // 将用户信息放入到session中
        MemberVO memberVO = r.getData("data", new TypeReference<MemberVO>() {});
        session.setAttribute(AuthConstant.SESSION_LOGIN_USER, memberVO);

        // 登录成功，重定向到首页
        return "redirect:http://yomall.com";
    }

    /**
     * 登录页面
     * @param session
     * @return
     */
    @GetMapping("/login.html")
    public String loginPage(HttpSession session) {
        Object attribute = session.getAttribute(AuthConstant.SESSION_LOGIN_USER);
        if (attribute != null) {
            return "redirect:http://yomall.com";
        }
        return "login";
    }
}
